using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Modules.NBrightEspace.Components;
using DotNetNuke.Services.Exceptions;
using NBrightCore.common;
using NBrightCore.render;
using NBrightDNN;

namespace DotNetNuke.Modules.NBrightEspace
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditNBrightEspace class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Tasks : EspaceModuleBase
    {

        #region Event Handlers

        private const string EntityTypeCode = "TASKS";

        override protected void OnInit(EventArgs e)
        {
            //Set base EntityTypeCode, MUST be done for all NBright child ctrls before OnInit
            base.EntityTypeCode = EntityTypeCode;

            base.OnInit(e);

            //initalize the repeater template based on what we want to see, a list or editing details.
            if (base.ItemId == "")
            {// itemid is blank so display the list
                rpData.Visible = false;

                //All list display functions are processed via the parent class, we just initiallize here.
                base.OnInitActivateList(true, true, MapPath(ControlPath));

            }
            else
            {// itemid is not blank, so display the detail template.
                base.OnInitDetail(rpData);
            }

        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (Page.IsPostBack == false)
            {
                PageLoad();
            }
        }

        private void PageLoad()
        {
            try
            {

                if (UInfo.SelType == "client")
                {// return to control from selection page.
                    base.UpdateSelected("client");
                    base.UpdateSelected("clientclear");
                }

                if (UInfo.SelType == "project")
                {// return to control from selection page.
                    base.UpdateSelected("project");
                    var selItemId = UInfo.SelItemId;
                    if (Utils.IsNumeric(selItemId))
                    {
                        var objPInfo = ObjCtrl.Get(Convert.ToInt32(selItemId));
                        if (objPInfo != null)
                        {
                            UInfo.SelItemId = objPInfo.GetXmlProperty("genxml/hidden/clientid");
                            if (Utils.IsNumeric(UInfo.SelItemId))
                            {
                                base.UpdateSelected("client");                                
                            }
                        }
                    }
                
                }
                if (UInfo.SelType == "website")
                {// return to control from selection page.
                    base.UpdateSelected("website");
                    var selItemId = UInfo.SelItemId;
                    if (Utils.IsNumeric(selItemId))
                    {
                        var objPInfo = ObjCtrl.Get(Convert.ToInt32(selItemId));
                        if (objPInfo != null)
                        {
                            UInfo.SelItemId = objPInfo.GetXmlProperty("genxml/hidden/clientid");
                            if (Utils.IsNumeric(UInfo.SelItemId))
                            {
                                base.UpdateSelected("client");
                            }
                        }
                    }

                }

                if (base.ItemId == "")
                {
                    // display list   
                    base.BindListData();
                }
                else
                {// display the detail
                    base.DoDetail(rpData);
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }



        #endregion

        #region  "Events "

        protected void CtrlItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "new":
                    Response.Redirect(EditUrl("itemid", "0", EntityTypeCode), true);
                    break;
                case "update":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "updateexit":
                    UpdateData();
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "addlog":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "sendemails":
                    UpdateData();
                    SendEmails();
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "cancel":
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "delete":
                    base.DeleteData(rpData);
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "selectclient":
                    UpdateData();
                    UInfo.SelType = "client";
                    UInfo.RtnSelUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.RtnUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.Save();
                    Response.Redirect(EditUrl("ClientSel"));
                    break;
                case "selectproject":
                    UpdateData();
                    UInfo.SelType = "project";
                    UInfo.RtnSelUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.RtnUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.Save();
                    Response.Redirect(EditUrl("ProjectSel"));
                    break;
                case "selectwebsite":
                    UpdateData();
                    UInfo.SelType = "website";
                    UInfo.RtnSelUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.RtnUrl = EditUrl("itemid", base.ItemId, EntityTypeCode);
                    UInfo.Save();
                    Response.Redirect(EditUrl("WebsiteSel"));
                    break;
                case "goclient":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", GenXmlFunctions.GetHiddenField(rpData, "ClientID"), "client"), true);
                    break;
                case "goproject":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", GenXmlFunctions.GetHiddenField(rpData, "ProjectID"), "project"), true);
                    break;
                case "gowebsite":
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", GenXmlFunctions.GetHiddenField(rpData, "websiteid"), "website"), true);
                    break;
                case "completed":
                    GenXmlFunctions.SetField(rpData, "chkCompleted","True");
                    MarkCompleted(cArg, "True");
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;
                case "uncompleted":
                    GenXmlFunctions.SetField(rpData, "chkCompleted","False");
                    MarkCompleted(cArg, "False");
                    UpdateData();
                    Response.Redirect(EditUrl("itemid", base.ItemId, EntityTypeCode));
                    break;

            }

        }

        public override void EventListItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var cArg = e.CommandArgument.ToString();

            switch (e.CommandName.ToLower())
            {
                case "markcompleted":
                    MarkCompleted(cArg, "True");
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
                case "marknotcompleted":
                    MarkCompleted(cArg,"False");
                    Response.Redirect(EditUrl(EntityTypeCode));
                    break;
            }
        }

        public override void EventBeforeBindListData(Repeater rpListData, string webServiceUrl = "")
        {
            //set default filter
            if (String.IsNullOrEmpty(UInfo.SearchClearAfter))
            {
                UInfo.SearchFilters = " and (([xmlData].value('(genxml/textbox/dtereminder)[1]', 'nvarchar(50)') <= '" + DateTime.Today.ToString("s") + "')) and (LOWER([xmlData].value('(genxml/checkbox/chkcompleted)[1]', 'nvarchar(50)')) != 'true') ";
                UInfo.SearchOrderby = " Order by [xmlData].value('(genxml/dropdownlist/ddlstatus)[1]', 'nvarchar(50)'),[xmlData].value('(genxml/textbox/dtereminder)[1]', 'nvarchar(50)') ";
                UInfo.Save();
            }
        }

        #endregion

        #region "presistance methods"

        private void MarkCompleted(string itemId,string value)
        {
            if (Utils.IsNumeric(itemId))
            {
                var objCtrl = new EspaceController();
                var oInfo = ObjCtrl.Get(Convert.ToInt32(itemId));
                if (oInfo!=null)
                {
                    var totalHours = oInfo.GetXmlProperty("genxml/hidden/totalhours");
                    var wasCompleted = oInfo.GetXmlPropertyBool("genxml/checkbox/chkcompleted");
                    var projectid = oInfo.GetXmlProperty("genxml/hidden/projectid");
                    if (Utils.IsNumeric(projectid) && Utils.IsNumeric(totalHours) && Convert.ToDecimal(totalHours, CultureInfo.GetCultureInfo("en-US")) > 0) // only change status if we have a time entered
                    {
                        var xrefid = projectid + "*" + oInfo.ItemID.ToString("");
                        oInfo.XMLData = GenXmlFunctions.SetGenXmlValue(oInfo.XMLData, "genxml/checkbox/chkcompleted", value, false);
                        oInfo.XMLData = GenXmlFunctions.SetGenXmlValue(oInfo.XMLData, "genxml/hidden/completeddate", DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture), false);
                        if (wasCompleted && value.ToLower() == "false")
                        {
                            // if it was completed and now not completed then we need to remove the times from the project (if assign)
                            var oEspaceCtrl = new EspaceController();
                            var objT = oEspaceCtrl.GetByGuidKey(PortalId,ModuleId,"PROJTIME",xrefid);
                            if (objT != null)
                            {
                                oEspaceCtrl.Delete(objT.ItemID);
                            }
                        }
                        if (!wasCompleted && value.ToLower() == "true")
                        {
                            var owner = oInfo.GetXmlProperty("genxml/radiobuttonlist/rblowner");
                            if (owner == "") owner = "TASKS";
                            // if it was not completed and now is completed then we need to add the times onto the project (if assign)
                            //create a time record for reporting.
                            var obj = new NBrightInfo();
                            obj.ItemID = -1;
                            obj.TypeCode = "PROJTIME";
                            //get template and populate with new data
                            var rpTime = GenXmlFunctions.InitRepeater(obj, TemplCtrl.GetTemplateData("PROJTIME_Detail.html", Utils.GetCurrentCulture()));
                            GenXmlFunctions.SetField(rpTime, "projectid", projectid);
                            GenXmlFunctions.SetField(rpTime, "txthours", totalHours.ToString(CultureInfo.InvariantCulture));
                            GenXmlFunctions.SetField(rpTime, "txtemployee", owner);
                            GenXmlFunctions.SetField(rpTime, "txtdate", DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture));
                            GenXmlFunctions.SetField(rpTime, "txtlog", oInfo.GetXmlProperty("genxml/hidden/taskref") + ": " + oInfo.GetXmlProperty("genxml/textbox/txttaskname"));
                            obj.GUIDKey = xrefid;

                            //Get format XML from new repeater so XML is created.
                            obj.XMLData = GenXmlFunctions.GetGenXml(rpTime);
                            // update and reassign id, so we don;t get duplicate
                            obj.ItemID = ObjCtrl.Update(obj);

                        }

                        // update project total time
                        EspaceFunctions.UpdateProjectTotalTime(Convert.ToInt32(projectid));

                    }                     

                    objCtrl.Update(oInfo);
                }
            }
        }

        private void UpdateData()
        {
                if (Page.IsValid)
                {
                    // Does standard update of template form
                    var objInfo = (NBrightInfo)base.UpdateDetailNoValidate(rpData, EntityTypeCode,"");


                    // Do any special updates that are required.
                    if (string.IsNullOrEmpty(GenXmlFunctions.GetHiddenField(rpData, "completeddate")) && (GenXmlFunctions.GetField(rpData, "chkcompleted").ToLower() == "true"))
                    {
                        var objCtrl = new EspaceController();
                        GenXmlFunctions.SetHiddenField(rpData, "completeddate", DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture));
                        objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);
                        objCtrl.Update(objInfo);
                    }

                    if (!string.IsNullOrEmpty(GenXmlFunctions.GetHiddenField(rpData, "completeddate")) && (GenXmlFunctions.GetField(rpData, "chkcompleted").ToLower() == "false"))
                    {
                        var objCtrl = new EspaceController();
                        GenXmlFunctions.SetHiddenField(rpData, "completeddate", "");
                        objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);
                        objCtrl.Update(objInfo);
                    }

                    if (string.IsNullOrEmpty(GenXmlFunctions.GetField(rpData, "TaskRef")))
                    {
                        //if ClientRef doesn't exist create it
                        var objCtrl = new EspaceController();
                        GenXmlFunctions.SetField(rpData, "TaskRef", "TK3" + objInfo.ItemID.ToString("000000") + "-" + Convert.ToString(DateTime.Now.Year).Substring(2, 2));
                        objInfo.XMLData = GenXmlFunctions.GetGenXml(rpData);
                        objCtrl.Update(objInfo);
                    }
                }
        }


        #endregion

        private void SendEmails()
        {
            string strEmail = "";
            string TaskName = GenXmlFunctions.GetField(rpData, "txtTaskName");
            string CompanyName = GenXmlFunctions.GetField(rpData, "CompanyName");

            var objCtrl = new EspaceController();
            var objSettings = objCtrl.GetByTypeCode("SETTINGS");
            objCtrl.Update(objSettings);

            // Send Email Report to Admin
            var fromEmail = objSettings.GetXmlProperty("genxml/textbox/txtfromemail");


            strEmail += "<html>";
            strEmail += "<body>";
            strEmail += "<div>";
            strEmail += "Company Name : " + CompanyName + "<br />";
            strEmail += "Task Name : " + TaskName + "<br />";
            strEmail += "Alarm Date : " + GenXmlFunctions.GetField(rpData, "dteReminder") + "<br />";
            var completed = GenXmlFunctions.GetField(rpData, "chkCompleted");
            if (completed.ToLower()=="true") strEmail += "<br /><b>COMPLETED</b><br /><br />";
            strEmail += "<br /><b>Task Description</b><br /><br />";
            strEmail += GenXmlFunctions.GetField(rpData, "txtTaskDesc").Replace(Environment.NewLine, "<br />");
            strEmail += "<br /><br /><b>History</b><br /><br />";
            strEmail += GenXmlFunctions.GetField(rpData, "auditLog").Replace(Environment.NewLine, "<br />");
            strEmail += "<br /><br />";
            strEmail += "<a href=\"" + Request.Url.AbsoluteUri + "\">Link to Task</a>";
            strEmail += "</div>";
            strEmail += "</body>";
            strEmail += "</html>";

            var mailto = "";

            var chkL = (CheckBoxList)rpData.Items[0].FindControl("chkEmail");
            for (int lp = 0; lp <= (chkL.Items.Count - 1); lp++)
            {
                if (chkL.Items[lp].Selected)
                {
                    mailto += chkL.Items[lp].Text + ";";
                }
            }
            if (mailto != "")
            {
                mailto = mailto.TrimEnd(';');
                DotNetNuke.Services.Mail.Mail.SendMail(fromEmail, mailto, "", "Task: " + CompanyName + " - " + TaskName, strEmail, "", "HTML", "", "", "", "");                
            }

        }

    }

}